package com.zjht.gmcc.bean.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspWriter;

import com.zjht.gmcc.bean.SessionListener; 
import com.zjht.gmcc.bean.model.UserSession;

public final class MySession { 
	private static final long serialVersionUID = 3188365780446948827L;

	// sesion名称
	public static final String USER = "user";// 用户

	public static final String USER_MENUID_ALL = "menuidall";// 用户所有菜单的id号,用逗号间隔，并以逗号结尾
	public static final String USER_MENUID = "menuid";// 用户当前页面设置的菜单
	public static final String USER_MENUID_CLICK = "menuid_click";// 用户当前点击的菜单

	public static final String USER_NAVIGATOR = "usernavigator";// 用户页面导航条(父菜单 -> 子菜单)
	public static final String USER_MODAL = "usermodal";// modal标志(1表示showmodal页面,0表示非showmodal页面)
	public static final String USER_MODAL_TRUE = "1";// modal页面
	public static final String USER_MODAL_FALSE = "0";// 非modal页面
 
	public static final String USER_AVATAR = "avatar";// 模拟用户

	// task
	public static final String TASK_MSGCOUNT = "msgcount";// top页消息数量
	public static final String TASK_FIRSTTASKLIST = "firsttasklist";// 首页main消息列表
	public static final String TASK_FIRSTRELOAD = "firstreload";// 首页首次加载reload

	// 补货时的IMEI集合
	public static final String VALID_IMEI = "validlist";
	public static final String VALID_SN = "validlistsn";
	public static final String INVALID_IMEI = "invalidlist";

	// 默认提示语
	public static final String MSG_NULL = "对不起！您提交的数据有问题。\\r\\r可能是您的网络不稳定，导致数据异常。\\r\\r请您检查网络是否断线，然后再重新提交。";

	private static boolean ValidJSP_Sevlet(HttpServletRequest request, String menuid, StringBuilder strErrorMsg) {
		try {
			HttpSession session = request.getSession();
			Object o_allmenuid = session.getAttribute(USER_MENUID_ALL);
			
			boolean isOK = true;

			if (o_allmenuid == null || menuid == null) {// 判断session是否有效
				strErrorMsg.append("对不起，您需要重新登录系统!");
				isOK = false;
			} else {// 判断权限
				String s_allmenuid = o_allmenuid.toString();
				isOK = false;
				if (s_allmenuid != null && s_allmenuid.length() > 0) {
					if (menuid.indexOf(",") == -1) {
						if (s_allmenuid.indexOf(menuid + ",") != -1) {
							isOK = true;
						}
					} else {
						String[] s_menuid = menuid.split(",");
						for (int i = 0; i < s_menuid.length; i++) {
							if (s_allmenuid.indexOf(s_menuid[i] + ",") != -1) {
								isOK = true;
								break;
							}
						}
					}
				}
				if (isOK) {
					String navigator = "";// 导航条
					if (menuid.indexOf(",") == -1) {
						String parentmenuid = MyParamUtil.getParentMenuID(menuid);
						if (parentmenuid != null) {
							navigator = MyParamUtil.getMenuName(parentmenuid) + " -&gt; " + MyParamUtil.getMenuName(menuid);
						}
					} else {// 如果页面允许多个menuid访问，则只显示用户点击菜单的menuid
						Object omenuid_click = session.getAttribute(USER_MENUID_CLICK);
						if (omenuid_click != null) {
							menuid = omenuid_click.toString();
							String parentmenuid = MyParamUtil.getParentMenuID(menuid);
							if (parentmenuid != null) {
								navigator = MyParamUtil.getMenuName(parentmenuid) + " -&gt; " + MyParamUtil.getMenuName(menuid);
							}
						}
					}
					session.setAttribute(USER_NAVIGATOR, navigator);
					// session.setAttribute(USER_MODAL, (isModal) ? USER_MODAL_TRUE : USER_MODAL_FALSE);
					session.setAttribute(USER_MENUID, menuid);
				} else {
					strErrorMsg.append("对不起！您无权访问此页面。");
					session.setAttribute(USER_NAVIGATOR, null);
					session.setAttribute(USER_MODAL, null);
					session.setAttribute(USER_MENUID, null);
				}
			}
			return isOK;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("MySession.java(ValidJSP_Sevlet) error");
			return false;
		}
	}

	// 验证JSP
	public static boolean ValidSession(HttpServletRequest request, javax.servlet.jsp.JspWriter out, String menuid) throws IOException {
		try {
			StringBuilder strErrorMsg = new StringBuilder();
			HttpSession session = request.getSession();
			boolean isOK = SessionListener.isOnline(session);

			if (isOK)
				isOK = ValidJSP_Sevlet(request, menuid, strErrorMsg);
			else
				strErrorMsg.append("对不起，您被迫下线。\\n\\r\\n\\r可能是因为您在本机上重复登录或有人在其他电脑上用此帐号登录了。\\n\\r\\n\\r如果您想继续使用系统，请您重新登录!");
			if (!isOK) {
				out.println(getScript(strErrorMsg.toString()));
				out.flush();
			}
			return isOK;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("MySession.java(ValidSession) error");
			return false;
		}
	}

	// 验证Servlet
	public static boolean ValidSessionServlet(HttpServletRequest request, PrintWriter out, String menuid) throws IOException {
		try {
			StringBuilder strErrorMsg = new StringBuilder();
			boolean isOK = ValidJSP_Sevlet(request, menuid, strErrorMsg);
			if (!isOK) {
				out.println(getScript(strErrorMsg.toString()));
				out.flush();
			}
			return isOK;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("MySession.java(ValidSessionServlet) error");
			return false;
		}
	}

	// 验证Servlet
	private static String getScript(String msg) {
		StringBuilder strErrorMsg = new StringBuilder();
		strErrorMsg.append("<script>checkModal();alert(\"");
		strErrorMsg.append(msg);
		strErrorMsg.append("\");if(isModal){window.close();}else{this.location.href='/logon.jsp';}");
		strErrorMsg.append("</script>");
		return strErrorMsg.toString();
	}

	public static boolean ValidDuty(HttpServletRequest request, String menuid) {
		try {
			HttpSession session = request.getSession();
			Object o_allmenuid = session.getAttribute(USER_MENUID_ALL);

			boolean isOK = true;

			if (o_allmenuid == null) {// 判断session是否有效
				isOK = false;
			} else {// 判断权限
				String s_allmenuid = o_allmenuid.toString();
				int i_flag = -1;
				if (s_allmenuid != null && s_allmenuid.length() > 0) {
					if (s_allmenuid.indexOf(menuid + ",") != -1) {
						i_flag = 1;
					}
				}
				if (i_flag == -1) {
					isOK = false;
				}
			}
			return isOK;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("MySession.java(ValidDuty) error");
			return false;
		}
	}

	/**
	 * 判断是否是社会渠道（省级或市级）
	 * @author dyh 2009-11-20
	 * @param request
	 * @return true：是社会渠道,false：不是社会渠道，或session为空
	 */
	public static boolean isSocialChannel(HttpServletRequest request) {
		String channeltype = getChanneltype(request);
		if (MyConstant.CHANNEL_SOCIAL_CITY.equals(channeltype) || MyConstant.CHANNEL_SOCIAL_PROV.equals(channeltype)) {
			return true;
		} else
			return false;
	}

	/**
	 * 判断是否是电子渠道（自有或合作）
	 * @author dyh 2009-11-20
	 * @param request
	 * @return true：是电子渠道,false：不是电子渠道，或session为空
	 */
	public static boolean isEChannel(HttpServletRequest request) {
		String channeltype = getChanneltype(request);
		if (MyConstant.CHANNEL_E_GMCC.equals(channeltype) || MyConstant.CHANNEL_E_SOCIAL.equals(channeltype)) {
			return true;
		} else
			return false;
	}

	/**
	 * 获取session中的导航条名称
	 * @author dyh 2009-11-06
	 * @param request
	 * @return 导航条名称
	 */
	public static String getNavigator(HttpServletRequest request) {
		String nav = "";
		HttpSession session = request.getSession();
		Object o = session.getAttribute(USER_NAVIGATOR);
		if (o != null)
			nav = o.toString();
		return nav;
	}

	/**
	 * 获取session中的当前菜单ID
	 * @author dyh 2009-11-06
	 * @param request
	 * @return 导航条名称
	 */
	public static String getMenuid(HttpServletRequest request) {
		String menuid = null;
		HttpSession session = request.getSession();
		Object o = session.getAttribute(USER_MENUID);
		if (o != null)
			menuid = o.toString();
		return menuid;
	}

	/**
	 * 弹出alert提示框(如果是modal，则关闭窗口)
	 * @author dyh 2009-11-15
	 * @param out
	 * @param alertmsg 提示框内容
	 */
	public static void alert(JspWriter out, String alertmsg) {
		alertOK(out, alertmsg, null);
	}

	/**
	 * 处理完成后弹出alert提示框。如果打开的是modal窗口，则刷新父窗口URL，否则刷新本窗口URL
	 * @author dyh 2009-11-15
	 * @param out
	 * @param alertmsg 提示框内容
	 * @param url 刷新窗口的URL
	 */
	public static void alert(JspWriter out, String alertmsg, String url) {
		MySession.alertOK(out, alertmsg, getURLScript(url));
	}

	/**
	 * 处理完成后弹出alert提示框，并返回returnvalue
	 * @author dyh 2009-11-21
	 * @param alertmsg 提示框内容
	 * @param returnvalue 返回父窗口的值
	 */
	public static void alertAndReturnValue(JspWriter out, String alertmsg, String returnvalue) {
		MySession.alertOK(out, alertmsg, (!MyFormat.isStrNull(returnvalue) ? "window.returnValue='" + returnvalue
				+ "';if(parent)parent.hideDiv();window.close();" : null));
	}

	/**
	 * 处理完成后弹出alert提示框，根据closewindow决定是否关闭窗口。不刷新页面
	 * @author dyh 2009-11-15
	 * @param out
	 * @param alertmsg 提示框内容
	 * @param closewindow true:关闭窗口；false:不关闭窗口
	 */
	public static void alert(JspWriter out, String alertmsg, boolean closewindow) {
		MySession.alertOK(out, alertmsg, (closewindow ? "window.close();" : null));
	}

	/**
	 * 处理完成后弹出alert提示框，并执行otherscript
	 * @author dyh 2009-11-15
	 * @param out
	 * @param alertmsg 提示内容
	 * @param otherscript 其他脚本
	 */
	public static void alertOK(JspWriter out, String alertmsg, String otherscript) {
		try {
			out.print(getScript(alertmsg, otherscript));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * JSP用户逻辑异常(非系统异常)时alert提示框
	 * @author dyh 2009-11-15
	 * @param request
	 * @param response
	 * @param menu 用户当前菜单ID
	 * @param alertmsg 逻辑错误名称(无须写“对不起”之类的字类)
	 * @param url 需要刷新的页面URL（如果不需要刷新，则为null）
	 */
	public static void errAlert(HttpServletRequest request, JspWriter out, String menu, String alertmsg, String url) {
		String errcode = LogUtil.getErrCode(LogUtil.ERRSOURCE_JSP, LogUtil.ERRTYPE_USER, menu);
		alert(out, getErrMsg(alertmsg, errcode), url);
		LogUtil.logErr(request, errcode);
	}

	/**
	 * JSP用户逻辑异常(非系统异常)时alert提示框(不需要刷新窗口)
	 * @author dyh 2009-11-15
	 * @param request
	 * @param response
	 * @param menu 用户当前菜单ID
	 * @param alertmsg 逻辑错误名称(无须写“对不起”之类的字类)
	 */
	public static void errAlert(HttpServletRequest request, JspWriter out, String menu, String alertmsg) {
		errAlert(request, out, menu, alertmsg, null);
	}

	/**
	 * 发生JSP系统异常时alert提示框
	 * @author dyh 2009-11-15
	 * @param request
	 * @param response
	 * @param menu 用户当前菜单ID
	 */
	public static void expAlert(HttpServletRequest request, JspWriter out, String menu) {
		String errcode = LogUtil.getErrCode(LogUtil.ERRSOURCE_JSP, LogUtil.ERRTYPE_SYS, menu);
		alert(out, getExpMsg(errcode));
		LogUtil.logErr(request, errcode);
	}

	/**
	 * 页面提交的参数为空，弹出警告框
	 * @author dyh 2010-06-11
	 */
	public static void alertNullParameter(JspWriter out) {
		alert(out, MySession.MSG_NULL);
	}

	/**
	 * 公共方法：alert脚本
	 * @author dyh 2011-3-11
	 * @param alertmsg 提示框内容
	 * @param otherscript 其他脚本
	 */
	public static String getScript(String alertmsg, String otherscript) {
		StringBuilder script = new StringBuilder();
		if (!MyFormat.isStrNull(alertmsg) || !MyFormat.isStrNull(otherscript)) {
			script.append("<script type='text/javascript'>");
			script.append("try{hideAllDiv();}catch(e){}");
			if (alertmsg != null && alertmsg.length() > 0) {
				script.append("alert('");
				script.append(alertmsg);
				script.append("');");
			}
			if (!MyFormat.isStrNull(otherscript)) {
				script.append(otherscript.toString());
			}
			script.append("if(window.name!='myiframe'&&isModal){window.close();}");
			script.append("</script>");
		}
		return script.toString();
	}

	/**
	 * 获取err逻辑错误alert内容
	 * @author dyh 2011-3-11
	 * @param alertmsg 提示框内容
	 * @param errcode 错误代码
	 */
	public static String getErrMsg(String alertmsg, String errcode) {
		return (MyFormat.isStrNull(alertmsg) || MyFormat.isStrNull(errcode)) ? "" : "对不起！" + alertmsg + "\\n\\n错误代码：" + errcode
				+ "\\n\\n请您稍后再试或将“错误代码”报告给管理员。";
	}

	/**
	 * 获取exp系统异常alert内容
	 * @author dyh 2011-3-11
	 * @param errcode 错误代码
	 */
	public static String getExpMsg(String errcode) {
		return MyFormat.isStrNull(errcode) ? "" : "对不起！系统出错了~\\n\\n错误代码：" + errcode + "\\n\\n请您稍后再试或将“错误代码”报告给管理员。";
	}

	/**
	 * 公共方法：url刷新页面脚本
	 * @author dyh 2011-3-11
	 * @param url
	 */
	public static String getURLScript(String url) {
		StringBuilder script = new StringBuilder();
		if (!MyFormat.isStrNull(url)) {
			script.append("if(isModal){window.close();}if(mywin){mywin.location.href='" + url + "';}");
		}
		return script.toString();
	}

	// 以下方法为获取session中的相关用户信息
	// 如果整型，缺省值为MyConstant.INT_NULL；如果字符串，缺省值为""，不会出现null

	/**
	 * 从session中获取UserSession对象
	 * @author dyh 2010-12-28
	 * @param session
	 * @return UserSession对象
	 */
	public static UserSession getUser(HttpSession session) {
		if (session == null) {
			return null;
		} else {
			Object oUser = session.getAttribute(USER);
			if (oUser != null) {
				return (UserSession) oUser;
			} else
				return null;
		}
	}

	/**
	 * 从session中获取用户ID
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为MyConstant.INT_NULL
	 */
	public static int getUserid(HttpSession session) {
		UserSession user = getUser(session);
		int userid = MyConstant.INT_NULL;
		if (user != null)
			userid = user.getUserid();
		return userid;
	}

	/**
	 * 从session中获取用户编码
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getUsercode(HttpSession session) {
		UserSession user = getUser(session);
		String usercode = "";
		if (user != null)
			usercode = user.getUsercode();
		return MyFormat.formatStr(usercode);
	}

	/**
	 * 从session中获取用户名称
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getUsername(HttpSession session) {
		UserSession user = getUser(session);
		String username = "";
		if (user != null)
			username = user.getUsername();
		return MyFormat.formatStr(username);
	}

	/**
	 * 从session中获取用户所在组织ID
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为MyConstant.INT_NULL
	 */
	public static int getOrgid(HttpSession session) {
		UserSession user = getUser(session);
		int orgid = MyConstant.INT_NULL;
		if (user != null)
			orgid = user.getOrgid();
		return orgid;
	}

	/**
	 * 从session中获取用户所在组织编码
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getOrgcode(HttpSession session) {
		UserSession user = getUser(session);
		String orgcode = "";
		if (user != null)
			orgcode = user.getOrgcode();
		return MyFormat.formatStr(orgcode);
	}

	/**
	 * 从session中获取用户所在组织名称
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getOrgname(HttpSession session) {
		UserSession user = getUser(session);
		String orgname = "";
		if (user != null)
			orgname = user.getOrgname();
		return MyFormat.formatStr(orgname);
	}

	/**
	 * 从session中获取用户所在组织类型
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为MyConstant.INT_NULL
	 */
	public static int getOrgtype(HttpSession session) {
		UserSession user = getUser(session);
		int orgtype = MyConstant.INT_NULL;
		if (user != null)
			orgtype = user.getOrgtype();
		return orgtype;
	}

	/**
	 * 从session中获取用户所在组织渠道类型
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getChanneltype(HttpSession session) {
		UserSession user = getUser(session);
		String channeltype = "";
		if (user != null)
			channeltype = user.getChanneltype();
		return MyFormat.formatStr(channeltype);
	}

	/**
	 * 获取session中的渠道类型ChannelType
	 * @author dyh 2009-11-19
	 * @param request
	 * @return ChannelType渠道类型
	 */
	public static String getChanneltype(HttpServletRequest request) {
		return getChanneltype(request.getSession());
	}

	/**
	 * 从session中获取用户所在部门ID
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为MyConstant.INT_NULL
	 */
	public static int getDeptid(HttpSession session) {
		UserSession user = getUser(session);
		int deptid = MyConstant.INT_NULL;
		if (user != null)
			deptid = user.getDeptid();
		return deptid;
	}

	/**
	 * 从session中获取用户所在部门名称
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getDeptname(HttpSession session) {
		UserSession user = getUser(session);
		String deptname = "";
		if (user != null)
			deptname = user.getDeptname();
		return MyFormat.formatStr(deptname);
	}

	/**
	 * 从session中获取用户权限ID
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为MyConstant.INT_NULL
	 */
	public static int getDutyid(HttpSession session) {
		UserSession user = getUser(session);
		int dutyid = MyConstant.INT_NULL;
		if (user != null)
			dutyid = user.getDutyid();
		return dutyid;
	}

	/**
	 * 从session中获取用户组织角色编码
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为""，不会出现null
	 */
	public static String getActorcode(HttpSession session) {
		UserSession user = getUser(session);
		String actorcode = "";
		if (user != null)
			actorcode = user.getActorcode();
		return MyFormat.formatStr(actorcode);
	}

	/**
	 * 从session中获取用户所在地区ID
	 * @author dyh 2010-12-28
	 * @param session
	 * @return 缺省值为MyConstant.INT_NULL
	 */
	public static int getAreaid(HttpSession session) {
		UserSession user = getUser(session);
		int areaid = MyConstant.INT_NULL;
		if (user != null)
			areaid = user.getAreaid();
		return areaid;
	}

	/**
	 * 从session中获取IMEI集合
	 * @author dyh 2010-12-31
	 * @return
	 */
	public static ArrayList<String> getValidIMEIList(HttpSession session) {
		return getIMEIList(session, VALID_IMEI);
	}

	/**
	 * 从session中获取IMEI集合
	 * @author dyh 2010-12-31
	 * @return
	 */
	public static ArrayList<String> getInValidIMEIList(HttpSession session) {
		return getIMEIList(session, INVALID_IMEI);
	}

	/**
	 * 从session中获取SN集合
	 * @author dyh 2010-12-31
	 * @return
	 */
	public static ArrayList<String> getValidSNList(HttpSession session) {
		return getIMEIList(session, VALID_SN);
	}

	/**
	 * 从session中获取IMEI集合
	 * @author dyh 2010-12-31
	 * @return
	 */
	private static ArrayList<String> getIMEIList(HttpSession session, String key) {
		ArrayList<String> imeilist = new ArrayList<String>();
		try {
			Object list = session.getAttribute(key);
			if (list != null) {
				imeilist = (ArrayList<String>) list;
			}
			session.removeAttribute(key);
		} catch (Exception e) {

		}
		return imeilist;
	}
}
